package org.acy.file.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;

/**
 * FastDfs工具类
 *
 * @author yust
 */
@Component
@Slf4j
public class FastDfsClientUtil {

    @Resource
    private FastFileStorageClient storageClient;

    /**
     * 上传
     *
     * @param data 数据
     * @param ext  拓展名
     */
    public String uploadOriginal(byte[] data, String ext) {
        log.debug("上传文件:{}", ext);
        // 文件扩展名
        StorePath storePath = this.storageClient.uploadFile(new ByteArrayInputStream(data), data.length, ext, null);
        return storePath.getFullPath();
    }


    /**
     * 下載文件
     *
     * @param name 文件名
     * @return 文件内容
     */
    public byte[] download(String name) {
        log.debug("下载文件:{}", name);
        int groupIndex = name.indexOf("/");
        String groupName = name.substring(0, groupIndex);
        String fileName = name.substring(groupIndex + 1);
        return storageClient.downloadFile(groupName, fileName, new DownloadByteArray());
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件访问地址
     */
    public void deleteFile(String fileUrl) {
        log.debug("删除文件:{}", fileUrl);
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.warn(e.getMessage());
        }
    }
}